package com.tencent.wxcloudrun.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.tencent.wxcloudrun.common.AESCBCUtil;
import com.tencent.wxcloudrun.common.WeChatUtil;
import com.tencent.wxcloudrun.config.SuccessResult;
import com.tencent.wxcloudrun.dao.UserMapper;
import com.tencent.wxcloudrun.dto.UserEntity;
import com.tencent.wxcloudrun.dto.UserInfoEntity;
import com.tencent.wxcloudrun.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxServiceImpl implements WxService {

    @Value(value = "${wx.appId}")
    private String APP_ID;

    @Value(value = "${wx.appAssert}")
    private String APP_ASSERT;

    @Resource
    UserMapper userMapper;

    @Override
    public JSONObject getSessionId(String code) {
        Map<String, Object> data = new HashMap<>();
        data.put("appid", APP_ID);
        data.put("secret", APP_ASSERT);
        data.put("js_code", code);
        data.put("grant_type", "authorization_code");
        String request = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
        JSONObject result = JSON.parseObject(request);
        return result;
    }

    /**
     *  解密用户数据
     * @param encryptedData
     * @param iv
     * @return
     */
    @Override
    public SuccessResult getUserInfo(String code, String encryptedData, String iv) {
//        JSONObject sessionAndOpenId = this.getSessionId(code);
        Map<String, Object> data = new HashMap<>();
        data.put("appid", APP_ID);
        data.put("secret", APP_ASSERT);
        data.put("js_code", code);
        data.put("grant_type", "authorization_code");
        String request = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
        JSONObject sessionAndOpenId = JSON.parseObject(request);
        if (sessionAndOpenId.get("session_key") == null || sessionAndOpenId.get("openid") == null) {
            return SuccessResult.LoginSuccess("登陆过期");
        }
        try {
            JSONObject userInfo = AESCBCUtil.decrypt(encryptedData, sessionAndOpenId.get("session_key").toString(), iv);
            log.info(userInfo.toString());
            log.info("----------用户信息解析成功---------");
            // 库里找一下是否含有该用户openId的用户，没有，则新增一个
            log.info(userInfo.get("openId").toString());
            Map<String, Object> mapperMap = new HashMap<>();
            mapperMap.put("userId", userInfo.get("openId"));
            UserEntity users = userMapper.SelectUserInfoById(mapperMap);
            if (users != null) {
                // 用户存在，直接登陆，返回token
                Map<String, Object> tokenData = new HashMap<>();
                tokenData.put("session_key", sessionAndOpenId.get("session_key").toString());
                tokenData.put("openId", users.getUserId());
                StpUtil.login(tokenData);
                Object token = StpUtil.getTokenInfo();
                Map<String, Object> userResult = new HashMap<>();
                userResult.put("token", token);
                userResult.put("user", users);
                return SuccessResult.LoginSuccess(userResult);
            }
            log.info("-----------需新增用户-------------");
            Map<String, Object> signInUserInfo = new HashMap<>();
            signInUserInfo.put("userId", userInfo.get("openId"));
            signInUserInfo.put("userName", WeChatUtil.RandomUUID(20));
            signInUserInfo.put("password", WeChatUtil.RandomUUID(18));
            signInUserInfo.put("nickName", userInfo.get("nickName"));
            signInUserInfo.put("avatarUrl", userInfo.get("avatarUrl"));
            signInUserInfo.put("gender", userInfo.get("gender"));
            log.info(signInUserInfo.toString());
            return SuccessResult.SignInSuccess();
        } catch (Exception e) {
            log.info("------用户数据解析失败----------");
            return SuccessResult.SystemError(e.toString());
        }

    }

    @Override
    public SuccessResult wxLogin(Map<String, Object> wxInfo) {
        Map<String, String> getSessionKeyAndOpenIdData = new HashMap<>();
        getSessionKeyAndOpenIdData.put("appid", APP_ID);
        getSessionKeyAndOpenIdData.put("secret", APP_ASSERT);
        getSessionKeyAndOpenIdData.put("js_code", wxInfo.get("code").toString());
        getSessionKeyAndOpenIdData.put("grant_type", "authorization_code");
        JSONObject getSessionAndOpenIdObj = JSON.parseObject(
                HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(getSessionKeyAndOpenIdData).body()
        );
        if (getSessionAndOpenIdObj.get("session_key") == null || getSessionAndOpenIdObj.get("openid") == null) {

        }
        return null;
    }
}
